#include "../include/snakeLogic.h"
#include "../include/snake.h"
#include "../include/debug.h"

int status			=	SNAKE_OK;
ulong frameDelay	=	FRAME_MS;

ulong _score		=	0;

void move(void);
void checkFood(void);
void checkDeath(void);
void setFrameMs(void);

void snakeInit(void)
{
	_snakeInit();

	//adding food
	addDrawable(&snakeFood);
	generateFood();

	//	set update screen rate
	setFrameMs();
	
	//	reset score
	_score	=	0;
}

void snakeDoLogic(void)
{
	//int i	=	0;
	ASSERT(theSnake.len > 0);
	
	move();					//	moving
	checkFood();			//	check object collisions
	checkDeath();			//	check self collisions
}

void move(void)
{
	snakeMove();

	/*	check bounds	*/// TODO: check for bounds
	if(theSnake.head->x > (LCD_WIDTH - BITMAP_W - 1))	// todo check
		theSnake.head->x	=	0;
	else if(theSnake.head->x < 0)//BITMAP_W)
		theSnake.head->x	=	(LCD_WIDTH - BITMAP_W - 1);

	if(theSnake.head->y > (LCD_HEIGHT - BITMAP_H - 1))			// todo check
		theSnake.head->y	=	0;
	else if(theSnake.head->y < 0)
		theSnake.head->y	=	(LCD_HEIGHT - BITMAP_H - 1);

	theSnake.head->x	-=	theSnake.head->x % BITMAP_W;
	theSnake.head->y	-=	theSnake.head->y % BITMAP_H;
}

void checkFood(void)
{
	//	eating
	if(checkCollision(theSnake.head, &snakeFood))
	{
		eatSound();

		snakeGrow();
		if(theSnake.len >= MAX_CHUNKS - 2)
		{
			winSound();
			status	=	SNAKE_WIN;
		}
		generateFood();
	}
}

void checkDeath(void)
{
	
	//	check loose
	if(snakeCollision(theSnake.head))
	{
		deathSound();
		status	=	SNAKE_LOOSE;
	}
}


int snakeStatus(void)
{
	return status;
}

void snakeDir(char dir)
{
	setSnakeDir(dir);
}

void scoreInc(void)
{
	_score	+=	((ulong)theSnake.speed) * 2;
}

ulong snakeScore(void)
{
	return _score;
}

void setFrameMs(void)
{
	frameDelay	=	FRAME_MS / theSnake.speed;
}

void snakeSpeedInc(void)
{
	if(theSnake.speed < MAX_SPEED)
	{
		++theSnake.speed;
		setFrameMs();
	}
}

void snakeSpeedDec(void)
{
	if(theSnake.speed > MIN_SPEED)
	{
		--theSnake.speed;
		setFrameMs();
	}
}

